//
//  RestListViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-24.
//  Copyright (c) 2014年 suplus. All rights reserved.
//
#define MaxReturnCount     10
#import "RestListViewController.h"
#import "NetworkAccessManager.h"
#import "RestListTableCustomCell.h"
#import "UIAlertView+Kirinrin.h"
#import "MJRefresh.h"
#import "UtilHelper.h"
#import "RestListCellFrame.h"

@interface RestListViewController ()<RestListTableCustomCellDelegate,MJRefreshBaseViewDelegate>
@property(strong, nonatomic)NSArray *tableData;
//@property (strong,nonatomic) RestListTableCustomCell *cusromecell;
@property(weak,nonatomic) MJRefreshFooterView *footer;
@property(weak,nonatomic) MJRefreshHeaderView *header;
@property(nonatomic,assign)int firstReturnCount;
@end


@implementation RestListViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupRefreshView];
    
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLineEtched;
    // Do any additional setup after loading the view.
    if (self.appDelegate.userType == UserTypeParent) {
        self.navigationController.title = @"托咐提醒";

    }else{
        self.navigationController.title = @"托咐提醒";

    }
    
//    [self loatRemoteData];
    
}

-(void)setupRefreshView
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    header.delegate = self;
    
    [header beginRefreshing];
    self.header = header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.delegate = self;
    self.footer = footer;
}
-(void)dealloc
{
    [self.header free];
    [self.footer free];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
//    NSMutableString *uriString = [NSMutableString stringWithString:kBaseUrl];
    NSString *uriString;
    if (self.appDelegate.userType == UserTypeParent) {
//        [uriString appendFormat:@"RestApplication/%@/queryWithChild.json", self.appDelegate.user[@"childId"]];
        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithChild.json", self.appDelegate.user[@"childId"]];
    }else{
//        [uriString appendFormat:@"RestApplication/%@/queryWithClass.json", self.appDelegate.user[@"kClassId"]];
        uriString = [NSString stringWithFormat:@"RestApplication/%@/queryWithClass.json", self.appDelegate.user[@"kClassId"]];
    }
    
    if ([refreshView isKindOfClass:[MJRefreshFooterView class]]) {
//        上拉刷新
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"key"]= self.appDelegate.accessKey;
        parameters[@"maxReturnCount"] = [NSNumber numberWithInt:MaxReturnCount];
        parameters[@"firstReturnCount"] = [NSNumber numberWithInt:self.firstReturnCount];
        NSLog(@"key====%@",parameters);
        
        [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
            
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                NSMutableArray *temp =[NSMutableArray arrayWithArray:self.tableData];
                
                [temp[0] addObjectsFromArray:[self sortTableData:responseObject[@"data"]][0]];
                [temp[1] addObjectsFromArray:[self sortTableData:responseObject[@"data"]][1]];

                self.tableData = temp;
                [self.tableView reloadData];
                self.firstReturnCount += MaxReturnCount;
                
            }else{
                [UIAlertView alertWithRemoteError:resultCode];
            }
            [self.footer endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"opernation: %@\nerror: %@", operation, error);
            [UIAlertView alertWithNetworkError];
            [self.footer endRefreshing];
        }];

    }else{
        //        下拉刷新
        self.firstReturnCount = 0;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"key"]= self.appDelegate.accessKey;
        parameters[@"maxReturnCount"] = [NSNumber numberWithInt:MaxReturnCount];
        parameters[@"firstReturnCount"] = [NSNumber numberWithInt:self.firstReturnCount];
        NSLog(@"key====%@",parameters);
        [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
            
            int resultCode = [responseObject[@"result"]intValue];
            if (resultCode == 0) {
                self.tableData = [self sortTableData:responseObject[@"data"]];
                [self.tableView reloadData];
                
                for (NSArray *dayArray in self.tableData) {
                    self.firstReturnCount +=dayArray.count;
                }
            }else{
                [UIAlertView alertWithRemoteError:resultCode];
            }
            [self.header endRefreshing];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"opernation: %@\nerror: %@", operation, error);
            [UIAlertView alertWithNetworkError];
            [self.header endRefreshing];
        }];

    }
}



-(NSArray *)sortTableData:(NSArray *)data{
    NSMutableArray *todayArray = [NSMutableArray array];
    NSMutableArray *beforeArray = [NSMutableArray array];
    
    [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"obj %@", obj);
        RestListCellFrame *restCellFrame  = [[RestListCellFrame alloc]init];
        restCellFrame.data = obj;
        if ([UtilHelper isSameDay:[UtilHelper formatDateString:obj[@"createTime"] :nil] date2:[NSDate date]]) {

//            [todayArray addObject:obj];
            [todayArray addObject:restCellFrame];
        }else{
            
            [beforeArray addObject:restCellFrame];
//            [beforeArray addObject:obj];
        }
    }];
    return @[todayArray, beforeArray];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;    {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.tableData[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RestListTableCustomCell *cell =[RestListTableCustomCell cellWithTableView:tableView];
//    self.cusromecell =  cell;
    cell.delegate = self;
    cell.restListCellFrame = _tableData[indexPath.section][indexPath.row];
    
    return cell;
}
#pragma mark - RestListTableCustomCell的代理方法
-(void)loadRevertDateDelete:(RestListTableCustomCell *)rltcCell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:rltcCell];
    NSLog(@"---%d---",indexPath.row);
//    NSArray * indexArray=[NSArray arrayWithObject:indexPath];
//    
    self.tableData[indexPath.section][indexPath.row]  = rltcCell.restListCellFrame;
//    [self.tableView beginUpdates];
    
    
    
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:indexPath
                                         atScrollPosition:UITableViewScrollPositionNone
                                                 animated:YES];
   //    [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
    
//    [self.tableView endUpdates];
}
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"====heightForRowAtIndexPath==");
//    self.cusromecell.data
    RestListCellFrame *restCellFrame = self.tableData[indexPath.section][indexPath.row];
    return restCellFrame.cellHeight;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *sectionName;
    switch (section)
    {
        case 0:
            sectionName = @"今天";
            break;
        case 1:
            sectionName = @"之前";
            break;
            // ...
        default:
            sectionName = @"";
            break;
    }
    return sectionName;
}


//- (IBAction)changeToReadAction:(id)sender {
//
//    if(self.appDelegate.userType == UserTypeTeacher){
//        self.view.userInteractionEnabled = NO;
//        
//        RestListTableViewCell *cell = (RestListTableViewCell*)[[[sender superview]superview]superview];
//        
//        NSString *uriString = [NSString stringWithFormat:@"RestApplication/%@/makeRead.json", cell.id];
//        NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
//        
//        [[NetworkAccessManager shareManagerWithCustomSetting]POST:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
//            
//            int resultCode = [responseObject[@"result"]intValue];
//            if (resultCode == 0) {
//                cell.data[kIsRead] = @(1);
//                [cell.status setEnabled:NO];
//                [cell.status setTitle:@"已阅" forState:UIControlStateDisabled];
//            }else{
//                [UIAlertView alertWithRemoteError:resultCode];
//            }
//            self.view.userInteractionEnabled = YES;
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"opernation: %@\nerror: %@", operation, error);
//            [UIAlertView alertWithNetworkError];
//            self.view.userInteractionEnabled = YES;
//        }];
//    }
//}
@end
